package unimelb.filesync.server.protocol;

import javax.crypto.SecretKey;

import unimelb.filesync.common.message.NetworkMessage;
import unimelb.filesync.common.message.PasswordMsg;
import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.network.AesEncryptedNetworkConnection;
import unimelb.filesync.common.network.NetworkConnection;
import unimelb.filesync.common.network.NetworkService;
import unimelb.filesync.common.protocol.IFileSyncPhase;

public class GetPasswordPhase implements IFileSyncPhase {
    private final ProtocolContext context;

    private final NetworkService networkService;

    public GetPasswordPhase(ProtocolContext context) {
        super();
        this.context = context;
        this.networkService = new NetworkService();
    }

    @Override
    public void execute() {
        System.out.println("Reading password");

        final SecretKey key = context.getObject(ProtocolContext.SECRET_KEY);
        final NetworkConnection connection = context.getObject(ProtocolContext.HOT_LINE_CONNECTION);
        final NetworkConnection aesConnection = new AesEncryptedNetworkConnection(connection, key);
        context.addObject(ProtocolContext.HOT_LINE_CONNECTION, aesConnection);
        
        final NetworkMessage msg = networkService.readMessage(aesConnection);
        if (msg == null) {
            System.exit(0);
        }

        final PasswordMsg content = msg.getContent();
        final String expectedPassword = context.getObject(ProtocolContext.PASSWORD);
        final String actualPassword = content.getPassword();
        if (!expectedPassword.equals(actualPassword)) {
            System.out.println("Wrong password, exiting");
            System.exit(0);
        }
    }

}
